package com.augrain.microframework.lock.strategy;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 超时策略获取
 *
 * @author biaoy
 * @date 2021/6/10
 * @since 1.0
 */
public class StrategyManager {
    //保存LockTimeoutStrategy的实例，避免每次都new对象
    private static final Map<Class<? extends LockTimeoutStrategy>, LockTimeoutStrategy> LOCK_TIMEOUT_STRATEGY_MAP = new ConcurrentHashMap<>();

    private static final Map<Class<? extends ReleaseTimeoutStrategy>, ReleaseTimeoutStrategy> RELEASE_TIMEOUT_STRATEGY_MAP = new ConcurrentHashMap<>();

    public static LockTimeoutStrategy getLockTimeoutStrategy(Class<? extends LockTimeoutStrategy> aClass) throws Exception {
        LockTimeoutStrategy lockTimeoutStrategy = LOCK_TIMEOUT_STRATEGY_MAP.get(aClass);
        if (lockTimeoutStrategy == null) {
            synchronized (aClass) {
                if (lockTimeoutStrategy == null) {
                    lockTimeoutStrategy = aClass.newInstance();
                    LOCK_TIMEOUT_STRATEGY_MAP.put(aClass, lockTimeoutStrategy);
                }
            }
        }
        return lockTimeoutStrategy;
    }

    public static ReleaseTimeoutStrategy getReleaseTimeoutStrategy(Class<? extends ReleaseTimeoutStrategy> aClass) throws Exception {
        ReleaseTimeoutStrategy releaseTimeoutStrategy = RELEASE_TIMEOUT_STRATEGY_MAP.get(aClass);
        if (releaseTimeoutStrategy == null) {
            synchronized (aClass) {
                if (releaseTimeoutStrategy == null) {
                    releaseTimeoutStrategy = aClass.newInstance();
                    RELEASE_TIMEOUT_STRATEGY_MAP.put(aClass, releaseTimeoutStrategy);
                }
            }
        }
        return releaseTimeoutStrategy;
    }
}
